package com.google.android.apps.skipbot;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;

public class SkipperPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
  static final String OPT_ROBOT_CONFIG = "robot_config_key";
  static final String OPT_ROBOT_GAIT = "robot_gait_key";

  static final String SKIPPER_SMALL = "skpr_small";
  static final String SKIPPER_LARGE = "skpr_large";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
      initSummary(getPreferenceScreen().getPreference(i));
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
  }

  @Override
  protected void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
  }

  static String getRobotConfig(Context context) {
    return PreferenceManager.getDefaultSharedPreferences(context).getString(OPT_ROBOT_CONFIG, SKIPPER_LARGE);
  }

  static String getRobotGait(Context context) {
    return PreferenceManager.getDefaultSharedPreferences(context).getString(OPT_ROBOT_GAIT, SKIPPER_LARGE);
  }

  private void initSummary(Preference p) {
    if (p instanceof PreferenceCategory) {
      PreferenceCategory pCat = (PreferenceCategory) p;
      for (int i = 0; i < pCat.getPreferenceCount(); i++) {
        initSummary(pCat.getPreference(i));
      }
    } else {
      updatePrefSummary(p);
    }
  }

  private void updatePrefSummary(Preference p){
    if (p instanceof ListPreference) {
        ListPreference listPref = (ListPreference) p;
        p.setSummary(listPref.getEntry());
    }

    if (p instanceof EditTextPreference) {
        EditTextPreference editTextPref = (EditTextPreference) p;
        p.setSummary(editTextPref.getText());
    }
  }

  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    updatePrefSummary(findPreference(key));
  }
}
